<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/18
 * Time: 15:05
 */

namespace app\index\controller;
use app\common\PlsDemo;
use app\draw\controller\Draw;
use fileutil\FileUtil;
use think\Db;
use app\index\model\Banner as BannerModel;
use think\Request;

use think\Loader;
use think\Url;
class Index
{
    public function tab(){
        //1客服 2手机号
        return ['code' => 200, 'message' => '列表', 'type' => 6,'mobile'=>'15245016157','bg'=>'https://lihai.xmdonkey.com/bg1.jpg','con'=>'西安市未央区保杨百货店成立于2019年08月11日，注册地位于陕西省西安市未央区玄武东路26号，法定代表人为张跃强。经营范围包括日用百货，服装鞋帽，箱包皮具，化妆品，日化用品，家居用品，床上用品，电子产品等等。'];
    }

    /**
     * 首页
     */
    public function index($member_id = 0)
    {

        writeLogAlipay('funile');
        $banner_list = Db::name('banner')->field('id,pic_url,jump_link,banner_type')->where(['status' => 1,'auding_status' => 2,'parent_id' => 7,'is_delete' => 1])->select()->toArray();
        if(!empty($banner_list)){
            foreach ($banner_list as &$v){
                if($v['banner_type'] == 1){

                }else{
                    $v['jump_link'] = Request::instance()->domain().Url::build('index/banner',['id' => $v['id']]);
                }
            }
        }
        $news_list = Db::name('news_type')
            ->alias('news_type')
            ->field('news_type.id type_id,news_type.type_name,news.id id,news.title')
            ->where('news_type.auding_status',2)
            ->where('news.auding_status',2)
            ->where('news_type.is_delete',1)
            ->where('news.is_delete',1)
            ->where('news.status',1)
            ->join('news','news_type.id = news.type_id','left')
            ->group('news_type.id')
            ->select();
        $others_bussiness = Db::name('web')->field('id,cat_name,describe,jump_link,pic_url')
            ->where('auding_status',2)
            ->where('parent_id',2)
            ->select();
        $nav = Db::name('single')->field('id,cat_name')->where('parent_id',0)->where('is_delete',1)->limit(10)->order('sort','asc')->select();
        $nav2 = Db::name('single2')->field('id,cat_name')->where('parent_id',0)->where('is_delete',1)->limit(10)->select();
        //$member_message = Db::name('member_message')->select();

        $message = Db::name('member_message')->where('type_id',1)->limit(30)->where('message_type',2)->order('id','desc')->field('id,content title')->select()->toArray();
        foreach ($message as &$v){
            $v['title'] = hideStr($v['title'],8,4);
        }
        $ad1 = Db::name('banner')->field('id,banner_type,pic_url,jump_link')->where('parent_id',13)->where('auding_status',2)->where('is_delete',1)->select()->toArray();
        if(!empty($ad1)){
            foreach ($ad1 as &$v1){
                if($v1['banner_type'] == 1){

                }else{
                    $v1['jump_link'] = Request::instance()->domain().Url::build('index/banner',['id' => $v1['id']]);
                }
            }
        }
        //$ad2 = Db::name('banner')->field('type,pic_url,jump_link')->where('parent_id',1)->where('auding_status',2)->where('is_delete',1)->select();
        $draw_time = (new Draw())->haha();
        $ad2 = Db::name('banner')->field('id,banner_type,type,pic_url,jump_link')->where('parent_id',1)->where('auding_status',2)->where('is_delete',1)->select()->toArray();
        if(!empty($ad2)){
            foreach ($ad2 as &$v2){
                if($v2['banner_type'] == 1){

                }else{
                    $v2['jump_link'] = Request::instance()->domain().Url::build('index/banner',['id' => $v2['id']]);
                }
            }
        }
        if(!empty($draw_time)){
            $draw_time['type'] = 2;
            $ad2[] = $draw_time;
        }


        if($draw_time){
            $on_off = 'Y';
        }else{
            $on_off = 'N';
        }
        $draw = Db::name('config')->where('varname','web_draw')->value('varvalue');
        $apply_bool = Db::name('config')->where('varname','apply_bool')->value('varvalue');
        $member_time = Db::name('member')->where('id',$member_id)->value('create_time');

        $is_click_1_count = Db::name('member_message')->where('member_id',$member_id)->where('is_click',1)->where('create_time','> time',$member_time)->count();

        //$this->delFileUnderDir();
        $message[] = ['id' => 99999,'title' => '欢迎使用小毛驴车管家'];

        return ['code' => 200 ,
            'message' => 'OK',
            'is_click_1_count' => $is_click_1_count,
            'banner_list' => $banner_list,
            'news_list' => $news_list,
            'others_bussiness_list' => $others_bussiness,
            'nav' => $nav,
            'nav2' => $nav2,
            'message_list' => $message,
            'ad1' => $ad1,
            'ad2' => $ad2,
            'draw' => $on_off,
            'apply_bool' => $on_off,
            'type' => 2
        ];
    }

    public function h(){
        $headers = Request::instance()->header();
       // halt($headers);
    }



    public function findNum($str=''){
        $str=trim($str);
        if(empty($str)){return '';}
        $reg='/(\d{3}(\.\d+)?)/is';//匹配数字的正则表达式
        preg_match_all($reg,$str,$result);
        if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){
            return $result[1][0];
        }
        return '';
    }


    public function a(){
        halt(json_decode(input('a'),true));
        static $a = 1;
        $a++;
        echo $a;
    }

    public function ji(){
        $find_shop_assignor_records = Db::name('order o')
            ->join('shop_assignor_records sar','o.id = sar.order_id')
            ->where('sar.order_id',397)
            ->find();
        halt($find_shop_assignor_records);
    }

    public function delFileUnderDir($dirName = '../runtime/log')
    {
        (new \FileUtil())->unlinkDir($dirName);
    }


    public function w_pay(){
        /**
         *
         * example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
         * 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
         * 请勿直接直接使用样例对外提供服务
         *
         **/
        require_once "../extend/w_pay/lib/WxPay.Api.php";
        require_once "../extend/w_pay/example/WxPay.JsApiPay.php";
        require_once "../extend/w_pay/example/WxPay.Config.php";
        require_once '../extend/w_pay/example/log.php';



//初始化日志
        $logHandler= new \CLogFileHandler("./logt/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

//打印输出数组信息
        function printf_info($data)
        {
            foreach($data as $key=>$value){
                echo "<font color='#00ff55;'>$key</font> :  ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
            }
        }

//①、获取用户openid
        try{

            $tools = new \JsApiPay();
            $openId = '2345254';

            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("test");
            $input->SetAttach("test");
            $input->SetOut_trade_no("sdkphp".date("YmdHis"));
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            printf_info($order);
            $jsApiParameters = $tools->GetJsApiParameters($order);


            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();
        } catch(\Exception $e) {
            \Log::ERROR(json_encode($e));
        }
    }

    public function notify(){
        require_once "../extend/w_pay/lib/WxPay.Api.php";
        require_once '../extend/w_pay/lib/WxPay.Notify.php';
        require_once "../extend/w_pay/example/WxPay.Config.php";
        require_once '../extend/w_pay/example/log.php';

//初始化日志
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $config = new \WxPayConfig();
        \Log::DEBUG("begin notify");
        $notify = new PayNotifyCallBack();
        $notify->Handle($config, false);
    }

    public function check(){
        $info = Request::instance()->header();
        return $info;
    }

    public function md5()
    {
        $ret = base64_encode('{
  "alg": "HS256",
  "typ": "JWT"
}');
        return json_decode((base64_decode($ret)));
    }

    public function ar(){
       $where =  [
            ['name', 'like', 'thinkphp%'],
            ['title', 'like', '%thinkphp'],
            ['id', '>', 0],
            ['status', '=', 1],
        ];
       halt($where);
    }

    public function u(){
        //2019-04-11 09:38:39
        $lowtime = mktime(9, 38, 39, 04, 11+280, 2019);
        $order_gift_count = Db::name('order_gift_count')->where('order_id',478)->select()->toArray();
        if(!empty($order_gift_count)){
            foreach ($order_gift_count as $kogc => $vogc){
                Db::name('order_gift_count')->where('id',$vogc['id'])->update(['start_time' => date('Y-m-d H:i:s',time()),'end_time' => date('Y-m-d H:i:s',time()+$vogc['day']*3600*24)]);
            }
        }
    }

    public function kaoni()
    {
        $a = 5;
        $b = 7;
        $a = 5 || $b = 6;
        echo $b;

    }

    public function mail($x)
    {
        Loader::import('PHPMailer.src.PHPMailer',EXTEND_PATH);
        Loader::import('PHPMailer.src.SMTP',EXTEND_PATH);
        //设置邮件发送的时间，如果不设置，则会显示其他区的时间
        date_default_timezone_set('PRC');
        $mail = new \PHPMailer();
        //是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
        $mail->SMTPDebug = 0;

        //使用smtp鉴权方式发送邮件，当然你可以选择pop方式 sendmail方式等 本文不做详解
        //可以参考http://phpmailer.github.io/PHPMailer/当中的详细介绍
        $mail->isSMTP();

        //smtp需要鉴权 这个必须是true
        $mail->SMTPAuth=true;

        //链接qq域名邮箱的服务器地址
        $mail->Host = 'smtp.qq.com';

        //设置使用ssl加密方式登录鉴权
        $mail->SMTPSecure = 'ssl';

        //设置ssl连接smtp服务器的远程服务器端口号 可选465或587
        $mail->Port = 465;

        //设置发件人的主机域 可有可无 默认为localhost 内容任意，建议使用你的域名,这里为默认localhost
        $mail->Hostname = 'http://shishurong.com';

        //设置发送的邮件的编码 可选GB2312
        $mail->CharSet = 'UTF-8';
        // ulrkfwxdyyeleaba
        //设置发件人姓名（昵称）可为任意内容，不影响回复(设置为qq昵称即可)
        $mail->FromName = '顶级购物商城';

        //smtp登录的账号 这里填入qq号即可
        $mail->Username ='2355308574';

        //smtp登录的密码 这里填入“独立密码” 若为设置“独立密码”则填入登录qq的密码 建议设置“独立密码”
        $mail->Password = 'dfdjyvwokauxeaed';

        //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”

        $mail->From = '2355308574@qq.com';

        //邮件正文是否以html方式发送
        $mail->isHTML(true);

        //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大

        $mail->addAddress($x,'');

        //可添加多个收件人
        //$mail->addAddress('XXXX@qq.com','XXXXX');

        //添加该邮件的主题
        $mail->Subject = '这是一个PHPMailer发送邮件的示例';

        //添加邮件正文
        $mail->Body = "这是一个<b style=\"color:red;\">PHPMailer</b>发送邮件的一个测试用例";

        //为该邮件添加附件 该方法也有两个参数 第一个参数为附件存放的目录（相对目录、或绝对目录均可）
        //第二参数为在邮件附件中该附件的名称
        // $mail->addAttachment('./src/20151002.png','test.png');

        //同样该方法可以多次调用 上传多个附件
        //$mail->addAttachment('./Jlib-1.1.0.js','Jlib.js');

        //发送命令 返回布尔值
        //PS：经过测试，要是收件人不存在.若不出现错误依然返回true也就是说在发送之前
        //自己需要些方法实现检测该邮箱是否真实有效
        $status = $mail->send();
        //简单的判断与提示信息
        if($status)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function alipay(){

        require_once ROOT_PATH.'extend/alipay/AopSdk.php';
        $aop = new \AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2018093061534902";
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDa18/7+WGpRtrwyYS9dYtUX+/rIqGWvaJwxghCgsYm1C61y+NPBM8NzSqeWj9LkEdPMpK2eEImhkoPiBaCdk5EPVmgBJdJLHLtBqoJ9rdaPCs0eaHDYH0wC02FyzcLIbaVx8ExVchlNHWkLy1FdMG3glcYub04cO5B7fiBEngwjaQThxzW6WkCJ2AZbEouPoZIZBaWQ3UVF9dOXRg/ft1n1HWB6uhV37kAIIvck99QyQqTJOciXBzyJxABB/Op6a25Jn5SfxOfT/6UodXajvL8K6Ntb9Ut/MDcO7yw0dACG4HnX6Jtx3SUql1PHtGLmLm4R2uX7ElHjSJrx/WQelRHAgMBAAECggEAVQiQZy8idHz0q6UR7/ARgGp6tdnSAdmTmdBI+1cHGaVOtRMRMu4CajFzQu58M6dPHgXfngkiYwfBFUHixTSk+rz/6z59blBYI6N4RMDZw7UncI9mfJ0sZ5OsvrUUoT2rTY29kqbrY++7Wl1+cMOKVfzOTOw3CwxOd824xqZfjzVx2FoXXXaIk4ujJpa1+LWQl8o+V7s9wHdrwm1nHSvZ/hbvn88AOlfCqMayTofeEtEBKCqkG9ctVJerSmb3tUN13k1Z2QN1iOU67eQwousUSnvcvJViY/4iqzKzzXD4bRPOs0MUp3//V2kmHLclkzut1OjP2h2oGqEycNa1X42XMQKBgQD85RbgX/7/sMxxCiGXtFmPIx3L/aJ+oreh6XJXEiBjIn/iuOecegk7HNEkCcR34T5q5TTzWPRueY2NQsOKeP53Xa88rM8RbA5eLkRlUV4jkvgZiws0jdXRaSTxfNbcTZ+sQHtWEe+a9GTQZEEG25ZJnjaAvRBAS2umzvkFQW9YLwKBgQDdh7CRei8VSKrRcPff86avF5LvKg9R3zAaRc+04GngR4M45MsKDu1poC7Apk3BGgoyXw2n+2+clDxCmB+doqWYCOXy26tMW5TTurVl7ctFzLRbEB9+PZEjh+e0l6XsxyuA0FeymiUrX4FXLObqvibMix2lnEjRCXfWaTb8OqAnaQKBgCtLvULkrG9yAU5JAb9LLRoIVQ2berpbeTzLDrxBajIOsf5K0bxEWFg6csPMuEod0eXTH+GZlR9kyAsrJvcKB+a/r0SgAUNmUH9nRGZkK83DV55n4583uSeE7MI7MT2+PFvtHjB6GZ9Zv/i9cTSPW4d3ArW/qIyZXPDN9mwj68AZAoGBAKhPzN5rB9TS9j3U5++2jmEftxqRSTx6J3D+s5YIn0iw7MlQQ9ericQj2QG0GQVrBG5K+/QyPBWqJrKuI+8/wTLnJ9bCAb8tIcFQbTw5VKT+p9U8RcFDg7+MJYZ3ZbCljq77HHZtWWo/0ORsEDIwMQhddjP6rvRrjipQnF89J6tpAoGBAOoPy2l3yMYYwot/TECjMBGoT/cmlNwVG1Sc9nK2tq1z92ei2k608XG70eM8IPi7vyks1w7SQQO375xJrs5Axnatg9U7MfyKJKJksS2RGByW03tuBilbBgNKjcosJh1ocsw6onTeajdsuijclDkxqmdbEk57OeBCER8T9vXMsWQI';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = '1MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVq5p4YpdrDmQ6O5QbMPuJhGna04fOiIyWOFQB4zafP3e24jscy8NSvGILigVSNMZkb8Uw2vu3qb5Bu4HpeFOlTCmiFJdbtpin/N/QWED79XTjzfRnl/IOe5fzH31JF3dFSUT3h0z+PTTpsmNTXF02DOEm7y7k3X4zdFwHRvq7ewadPBDJdDOTjZTtWuSD3H4jP21ljvNzS/j9mEvxHEiRJ5z4AuQeT1P3AzchLxZLGAx0TnoYIzeseK9/k6NYcxJY3C9OyXkWQhBO0/HnB4arkKW2BMrTQ246uBpakVrzRBwKcjCYIJgiHE4G9Fu6hKqI+u2dhLtKcpQRojFi10QwIDAQABMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVq5p4YpdrDmQ6O5QbMPuJhGna04fOiIyWOFQB4zafP3e24jscy8NSvGILigVSNMZkb8Uw2vu3qb5Bu4HpeFOlTCmiFJdbtpin/N/QWED79XTjzfRnl/IOe5fzH31JF3dFSUT3h0z+PTTpsmNTXF02DOEm7y7k3X4zdFwHRvq7ewadPBDJdDOTjZTtWuSD3H4jP21ljvNzS/j9mEvxHEiRJ5z4AuQeT1P3AzchLxZLGAx0TnoYIzeseK9/k6NYcxJY3C9OyXkWQhBO0/HnB4arkKW2BMrTQ246uBpakVrzRBwKcjCYIJgiHE4G9Fu6hKqI+u2dhLtKcpQRojFi10QwIDAQAB';
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"body\":\"我是测试数据\","
            . "\"subject\": \"App支付测试\","
            . "\"out_trade_no\": \"20170125test01\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"FACE_TO_FACE_PAYMENT\""
            . "}";
        $request->setNotifyUrl("商户外网可以访问的异步地址");
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        echo htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        $resultCode = $response->$responseNode->code;

        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }

    public function axb(){
        $args = ['noa' => 15245016157,'nob' => 15561827713,'nox' => 17000000000,'expect_city' => '北京','expire_time' => 120];
      return PlsDemo::bindAxb($args);
    }

    public function ha(){
        halt($_SERVER['REMOTE_ADDR']);
    }

    public function uu(){
        $data = Db::name('order_gift_count')->where('single_content','eq','168')->select();
        if(!empty($data)){
            foreach ($data as $v){
                $ret['168'][] = $v['id'];
                Db::name('order_gift_count')->where('single_content',$v['single_content'])->setField('single_content',10020);
            }
        }
        $data2 = Db::name('order_gift_count')->where('single_content','eq','174')->select();
        if(!empty($data2)){
            foreach ($data2 as $v2){
                $ret[174][] = $v2['id'];
                Db::name('order_gift_count')->where('single_content',$v2['single_content'])->setField('single_content',10024);
            }
        }
        return $ret;
    }


    public function member()
    {
        $data = Db::table('sun_member')->where('id','in','2,35')->column('id');

        foreach ($data as &$v444){
            $v444 = (string)$v444;
        }
        $data2 = array_chunk($data, 2);

        //dump($data2);

        foreach ($data2 as &$v) {
           // $v = implode(',', $v);
//            foreach($v as $v2){
//                $v2 = (string)$v2;
//            }

           (new \app\index\controller\MemberMessage())->jpushMessage_alias($v, '1', '2', 1);
        }

        return json($data2);
    }

    public function banner($id)
    {
        $data = Db::name('banner')->where('id', $id)->value('content');
        $content = '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">';
        $content .= '<style> img {vertical-align:middle; width:auto; max-width:100%;} *{margin:0;padding:0}</style>';
        $content .= $data;
        return \think\Response::create($content, 'html');
    }

    public function sign()
    {
        $appid = "YOUR APPID_ID";
        $bucket = "tencentyun";
        $secret_id = "YOUR SECRET_ID";
        $secret_key = "YOUR SECRET_KEY";
        $expired = time() + 2592000;
        $onceExpired = 0;
        $current = time();
        $rdm = rand();
        $userid = "0";
        $fileid = "tencentyunSignTest";

        $srcStr = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $expired . '&t=' . $current . '&r=' . $rdm . '&f=';

        $srcWithFile = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $expired . '&t=' . $current . '&r=' . $rdm . '&f=' . $fileid;

        $srcStrOnce = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $onceExpired . '&t=' . $current . '&r=' . $rdm
            . '&f=' . $fileid;
    }

    public function upload(){

    }

    public function haha(){
        (new \app\index\controller\MemberMessage())->jpushMessage_alias('35', '收不到信息么', '收不到信息么', 1);
//        $member_list = Db::name('member')->where('id','in',[15])->field('id')->select()->toArray();
//        foreach ($member_list as &$v444){
//
//            $v444 = (string)$v444['id'];
//        }
//        $member_list2 = array_chunk($member_list, 1000);
//
//        foreach ($member_list2 as $k =>&$v123) {
//
//
//           //dump($v123);
//           //$v123 = ['1','2','3','4','5'];
//           //https://api.jpush.cn/v3/push/validate
//
//        }

    }

    public function ajax(){
        return view();
    }

    public function m(){
        $out_trade_no = '201909191411449320525424';
        $out_trade_no = '201909191352114103235731'; //3185 3187
        $out_trade_no = '201909200845491606031723';
        $out_trade_no = '201909201015467711206927';
        $order = Db::name('order')->where('order_number',$out_trade_no)->find();//订单所有数据
        dump($order['member_id']);
        $manage_id = Db::name('share_member')->where('member_id',$order['member_id'])->value('manage_id');//获得直属业务员
        dump($manage_id);
        $manage_id = 1;
        dump($manage_id);

        if(!empty($manage_id)){

            $salesman_array = parentPath($manage_id,'salesman',true); //当前业务员上级
            dump($salesman_array);
            $salesman_list = array_reverse($salesman_array);

            dump($salesman_list);
            // $salesman_list = array_slice($salesman_array,0,3);
            if(!empty($salesman_list)){

                $pre = 0;
                foreach ($salesman_list as $k => $v){
                    $amount = Db::name('order')->where(['order_number|shop_order_number' => $out_trade_no])->sum('amount');//订单总额
                    if($k > 2) break;
                    $zhishu = Db::name('manager')->where('id',$v['manage_id'])->value('per');//直接销售比~
                    if(is_null($zhishu) || $k != 0) $zhishu = 0;

                    if($k == 0)  $pre = Db::name('config')->where('varname','web_d'.($k+1))->value('varvalue');
                    if($k == 1)  $pre = Db::name('config')->where('varname','web_d'.($k+1))->value('varvalue');
                    if($k == 2)  $pre = Db::name('config')->where('varname','web_d'.($k+1))->value('varvalue');

                    $single_per = 0;
                    $per_order = Db::name('order')->where(['order_number|shop_order_number' => $out_trade_no])->group('order_number')->select();//~订单列用于商品列表 没必要2次循环 一次就查出多单数据 否则总单会多次循环
                    //$alipaySevice->writeLog('$per_order'.$v['manage_id'].'-'.json_encode($per_order));
                    foreach ($per_order as $ko => $vo){
                        if($vo['order_type'] == 1){ //商品
                            $order_goods =  Db::name('order_goods')->where(['order_number|shop_order_number' => $out_trade_no])->select();
                            foreach ($order_goods as $ko1 => $vo1){
                                $s_p = Db::name('salesman_price')->where('salesman_id',$v['manage_id'])->where('type_pk_id',$vo1['goods_id'])->where('type',$vo['order_type'])->value('per')/100;
                                if(is_null($s_p)) $s_p = 0;
                                //$alipaySevice->writeLog('1single_per'.$v['manage_id'].'-'.$single_per);
                                $single_per += $vo1['price']*$vo1['number']*$s_p;//价钱*数量*分销比 独立销售比例

                            }
                        }
                        if($vo['order_type'] == 2){ //礼包
                            $s_p = Db::name('salesman_price')->where('salesman_id',$v['manage_id'])->where('type_pk_id',$order['single_id'])->where('type',$vo['order_type'])->value('per')/100;
                            if(is_null($s_p)) $s_p = 0;
                            $single_per = $order['amount']*$s_p;
                        }
                        if($vo['order_type'] == 3){ //礼包
                            $s_p = Db::name('salesman_price')->where('salesman_id',$v['manage_id'])->where('type_pk_id',$order['gift_id'])->where('type',$vo['order_type'])->value('per')/100;
                            if(is_null($s_p)) $s_p = 0;
                            //$alipaySevice->writeLog('3sp'.$s_p);
                            //$alipaySevice->writeLog('3single_per'.$single_per);
                            $single_per = $order['amount']*$s_p;
                        }
                    }
                    $insert = [
                        'order_number' => $order['order_number'],
                        'manage_id' => $v['manage_id'],
                        'order_type' => $order['order_type'],
                        'member_id' => $order['member_id'],
                        'amount' => $amount,
                        'price' => $amount*$pre/100,
                        'per' => $amount*$zhishu/100,
                        'single_per' => $single_per,
                        'create_time' => $order['create_time']
                    ];
                    Db::name('member_distribution_records')->insert($insert);
                }
            }
        }
        halt(2);
    }

    public function ma(){
        $member_list = Db::name('member')->limit(2)->field('id')->select()->toArray();
        foreach ($member_list as $k => $v){
            $insertAll[] = [
                'member_id' => $v['id'],
                'title' => 'titles',
            ];
            $member_args[] = (string)($v['id']);

            //(new \app\index\controller\MemberMessage())->jpushMessage(35,$data['title'],strip_tags($data['content']),1);
        }
        foreach ($member_list as &$v444){

            $v444 = (string)$v444['id'];
        }


        $insertAll = array_chunk($insertAll,2);

        foreach ($insertAll as $vi){

            (new \app\index\model\MemberMessage())->insertAll($vi);

        }


    }


    /**
     * 导入EXCEL
     */
    public function excelToArray()
    {
        // dirname(__FILE__) .
        $rule = require_once '../extend/phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php';

        // import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        //$objPHPExcel = new \PHPExcel();
        //加载excel文件
        $filename = './KingDee (123).xlsx';

        $objPHPExcelReader = \PHPExcel_IOFactory::load($filename);
        $sheet = $objPHPExcelReader->getSheet(1);        // 读取第一个工作表(编号从 0 开始)
        $highestRow = $sheet->getHighestRow();           // 取得总行数
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数

        $arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        // 一次读取一列
        $res_arr = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            $row_arr = array();
            for ($column = 0; $arr[$column] != 'U'; $column++) {
                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                $row_arr[] = $val;
            }

            $res_arr[] = $row_arr;
        }

        \think\Cache::set('excel_data', $res_arr);

        //return $res_arr;

    }

    public function p($data = [], $name = 'Excel')
    {

        $data[] = ['font' => 'wenzi','num' => '1234'];
        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '一级分类')
            ->setCellValue('C1', '二级分类')
            ->setCellValue('D1', '买家账号')
            ->setCellValue('E1', '会员车牌号')
            ->setCellValue('F1', '订单车牌号')
            ->setCellValue('G1', '是否认证')
            ->setCellValue('H1', '下单/退款时间')
            ->setCellValue('I1', '消费门店')
            ->setCellValue('J1', '订单总额')
            ->setCellValue('K1', '订单状态')
            ->setCellValue('L1', '创建时间')
            ->setCellValue('M1', '订单详情')
        ;

        $sheet1 = [];


        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['font'])
                ->setCellValue('B' . $num, ' '.$v['num'])
            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('订单信息导出');
        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');
        exit;
    }

    public function tui(){
        (new \app\index\controller\MemberMessage())->jpushMessage_alias(['2969'], '1', '2', 1);
    }



    public function che(){
        $data = Db::name('gift_card')->field('count(*) as c,card_num')->group('card_num')->order('c desc')->select()->toArray();
        $arr = [];
        $arr2 = [];
        foreach ($data as $v){
            if($v['c'] == 2){
                //$arr[] = Db::name('gift_card')->field('id,gift_id,order_id,card_num,status')->where('card_num',$v['card_num'])->select()->toArray();
                $a = Db::name('gift_card')->field('id,gift_id,order_id,card_num,status')->where('status',1)->where('card_num',$v['card_num'])->select()->toArray();
                if($a){
                    $arr2[] = $a;
                }

            }
        }
        halt($arr2);
        $arr3 = [];
        foreach ($arr2 as $v1){
            $db = Db::name('gift_card')->where('id',$v1[0]['id'])->delete();
            if($db){
                $arr3[] = $v1[0]['id'];
            }
            //halt(1);
        }
        halt($arr3);
    }





}


